<template>
  <ElForm
    style="display: inline-block; width: 100%"
    :inline="true"
    ref="Mikeform"
    @submit.prevent
    :model="formFields"
    :rules="rules"
    :label-width="110"
  >
    <div class="title">
      <span>类型</span>
    </div>
    <div class="form-item">
      <ElFormItem label="生成类型：" prop="generateType">
        <ElSelect
          v-model="formFields.generateType"
          style="width: 100%"
          filterable
          placeholder="请选择类型"
          @change="handleChangeValue"
        >
          <ElOption
            v-for="items in generateTypeList"
            :key="items.key"
            :label="items.value"
            :value="items.key"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="数据区域：" prop="region_idz">
        <ElSelect
          v-model="formFields.region_idz"
          style="width: 100%"
          filterable
          clearable
          placeholder="请选择数据区域"
        >
          <ElOption
            v-for="items in regionIdZList"
            :key="items.key"
            :label="items.value"
            :value="items.key"
          />
        </ElSelect>
      </ElFormItem>
      <div class="title">
        <span>表</span>
      </div>
      <div class="form-item">
        <ElFormItem :label="formFields.generateType == 0 ? '表名：' : '主名'" prop="tableNameZ">
          <ElInput
            v-model="formFields.tableNameZ"
            :placeholder="formFields.generateType == 0 ? '请输入表名' : '请输入主名'"
          />
        </ElFormItem>

        <ElFormItem v-if="formFields.generateType == 0" class="button">
          <ElButton type="primary" :loading="loadingIcon" @click="getForm(Mikeform)">验证</ElButton>
        </ElFormItem>

        <ElFormItem label="子名：" prop="tableNameC" v-if="formFields.generateType == 1">
          <ElInput v-model="formFields.tableNameC" placeholder="请输入子名" />
        </ElFormItem>
      </div>
      <div class="form-item" v-if="formFields.generateType == 1">
        <ElFormItem label="主表字段：" prop="relevanceZ">
          <ElInput v-model="formFields.relevanceZ" placeholder="请输入主表字段" />
        </ElFormItem>
        <ElFormItem label="子表字段：" prop="relevanceC">
          <ElInput v-model="formFields.relevanceC" placeholder="请输入子表字段" />
        </ElFormItem>
      </div>
      <ElFormItem class="full" v-if="formFields.generateType == 1">
        <ElButton type="primary" :loading="loadingIcon" @click="getForm(Mikeform)">验证</ElButton>
      </ElFormItem>
    </div>
    <div class="title">
      <span>构造</span>
    </div>
    <div class="form-item">
      <ElFormItem label="包名：">
        <ElInput v-model="formFields.parameter1" placeholder="请输入包名" />
      </ElFormItem>
      <ElFormItem :label="formFields.generateType == 0 ? '表单：' : '主表表单：'">
        <ElInput
          v-model="formFields.parameter2"
          :placeholder="formFields.generateType == 0 ? '请输入表单' : '请输入主表表单'"
        />
      </ElFormItem>
    </div>
    <div class="form-item">
      <ElFormItem :label="formFields.generateType == 0 ? '组合：' : '主表组合：'">
        <ElInput
          v-model="formFields.parameter3"
          :placeholder="formFields.generateType == 0 ? '请输入组合' : '请输入主表组合'"
        />
      </ElFormItem>
      <ElFormItem :label="formFields.generateType == 0 ? '查询：' : '主表查询：'">
        <ElInput
          v-model="formFields.parameter4"
          :placeholder="formFields.generateType == 0 ? '请输入查询' : '请输入主表查询'"
        />
      </ElFormItem>
    </div>
    <div class="form-item">
      <ElFormItem :label="formFields.generateType == 0 ? '列表：' : '主表列表：'">
        <ElInput
          v-model="formFields.parameter5"
          :placeholder="formFields.generateType == 0 ? '请输入列表' : '请输入主表列表'"
        />
      </ElFormItem>
      <ElFormItem v-if="formFields.generateType == 1" label="子表组合：">
        <ElInput v-model="formFields.parameter6" placeholder="请输入子表组合" />
      </ElFormItem>
    </div>
    <div class="form-item" v-if="formFields.generateType == 1">
      <ElFormItem label="子表列表：">
        <ElInput v-model="formFields.parameter7" placeholder="请输入子表列表" />
      </ElFormItem>
    </div>
    <template v-if="fieldTable?.length">
      <div class="title">
        <span>字段</span>
      </div>
      <div class="table_content_tables">
        <ElTable
          ref="TablesData"
          :data="fieldTable"
          style="width: 100%"
          :max-height="320"
          border
          table-layout="fixed"
          @selection-change="handleSelectionChange"
        >
          <ElTableColumn type="selection" width="55" />
          <ElTableColumn prop="parameter_key" label="字段" />
          <ElTableColumn prop="parameter_name" label="说明" />
          <ElTableColumn prop="parameter_type" label="字段属性" />
          <ElTableColumn prop="parameter_keyzu" label="是否主键">
            <template #default="scope">
              <span>{{ scope.row.parameter_keyzu == 0 ? '否' : '是' }}</span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="parameter_keytype" label="系统操作类型">
            <template #default="scope">
              <span>{{
                scope.row.parameter_keytype == 0
                  ? '字符串'
                  : scope.row.parameter_keytype == 1
                  ? '日期时间'
                  : scope.row.parameter_keytype == 2
                  ? '数字'
                  : scope.row.parameter_keytype
              }}</span>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </template>
    <template v-if="ChildfieldTable?.length">
      <div class="title" style="margin-top: 20px">
        <span>子表字段</span>
      </div>
      <div class="table_content_tables">
        <ElTable
          ref="TablesData"
          :data="ChildfieldTable"
          style="width: 100%"
          :max-height="320"
          border
          table-layout="fixed"
          @selection-change="handleSelectionChangeChild"
        >
          <ElTableColumn type="selection" width="55" />
          <ElTableColumn prop="parameter_key" label="字段" />
          <ElTableColumn prop="parameter_name" label="说明" />
          <ElTableColumn prop="parameter_type" label="字段属性" />
          <ElTableColumn prop="parameter_keyzu" label="是否主键">
            <template #default="scope">
              <span>{{ scope.row.parameter_keyzu == 0 ? '否' : '是' }}</span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="parameter_keytype" label="系统操作类型">
            <template #default="scope">
              <span>{{
                scope.row.parameter_keytype == 0
                  ? '字符串'
                  : scope.row.parameter_keytype == 1
                  ? '日期时间'
                  : scope.row.parameter_keytype == 2
                  ? '数字'
                  : scope.row.parameter_keytype
              }}</span>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </template>
    <template v-if="fieldTable?.length || ChildfieldTable?.length">
      <div class="form-item" style="margin-top: 20px">
        <ElFormItem class="full">
          <ElButton style="width: 100px" type="primary" :loading="loadingIcon" @click="generate"
            >生成</ElButton
          >
        </ElFormItem>
      </div>
    </template>
  </ElForm>
</template>

<script lang="ts" setup>
  import useLoading from '@/hooks/loading';
  import { throttle } from 'lodash-es';
  import type { FormInstance, FormRules } from 'element-plus';
  const { loadingIcon, setLoading } = useLoading();
  import { regionidzType } from '@/types';
  import { getTabledatas, Postgeneratepage } from '@/api/Unitregein';
  const Mikeform = ref<FormInstance | any>();
  const numberValue = ref<number>(1);
  const TablesData = ref<any>();
  const fieldTable = ref<Array<Namespace.tabledatasType>>();
  const ChildfieldTable = ref<Array<Namespace.tabledatasType>>();
  const MultiSelectDataFirst = ref<Array<Namespace.tabledatasType>>([]);
  const MultiSelectDataNth = ref<Array<Namespace.tabledatasType>>([]);
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:value', val: boolean): void;
  }
  const props = defineProps({
    regionIdZList: {
      type: Array<regionidzType>,
    },
    regionId: {
      type: Number,
    },
    dataTree: {
      type: String,
      default: '',
    },
  });
  const generateTypeList = ref<Array<regionidzType>>([
    {
      key: 0,
      value: '单表',
    },
    {
      key: 1,
      value: '多表',
    },
  ]);
  const formFields = reactive({
    generateType: 0,
    region_idz: '',
    tableNameZ: '',
    parameter1: '',
    parameter2: '',
    parameter3: '',
    parameter4: '',
    parameter5: '',

    parameter6: '',
    parameter7: '',
    relevanceC: '',
    relevanceZ: '',
    tableNameC: '',
  });

  const rules = reactive<FormRules>({
    generateType: [{ required: true, message: '请选择类型', trigger: 'change' }],
    region_idz: [{ required: true, message: '请选择数据区域', trigger: 'change' }],
    tableNameZ: [
      {
        required: true,
        message: formFields.generateType == 0 ? '请输入表名' : '请输入主名',
        trigger: 'blur',
      },
    ],
    tableNameC: [
      {
        required: true,
        message: '请输入子名',
        trigger: 'blur',
      },
    ],
    relevanceZ: [
      {
        required: true,
        message: '请输入主表字段',
        trigger: 'blur',
      },
    ],
    relevanceC: [
      {
        required: true,
        message: '请输入子表字段',
        trigger: 'blur',
      },
    ],
  });
  const handleChangeValue = async (value) => {
    if (value === 1 || value === 0) {
      formFields.tableNameZ = '';
      formFields.tableNameC = '';
      formFields.relevanceZ = '';
      formFields.relevanceC = '';
      formFields.parameter1 = '';
      formFields.parameter2 = '';
      formFields.parameter3 = '';
      formFields.parameter4 = '';
      formFields.parameter5 = '';
      formFields.parameter6 = '';
      formFields.parameter7 = '';
      fieldTable.value = [];
      ChildfieldTable.value = [];
      MultiSelectDataFirst.value = [];
      MultiSelectDataNth.value = [];
    }
  };
  const getForm = throttle(async (formEl: FormInstance | undefined) => {
    setLoading(true);
    if (!formEl) return;
    await formEl.validate(async (valid) => {
      if (valid) {
        formFields.parameter1 = formFields.tableNameZ + '_bag';
        formFields.parameter2 = formFields.tableNameZ + '_form';
        formFields.parameter3 = formFields.tableNameZ + '_group';
        formFields.parameter4 = formFields.tableNameZ + '_query';
        formFields.parameter5 = formFields.tableNameZ + '_list';
        const { data } = await getTabledatas({
          unit_code: formFields.tableNameZ,
          region_id: formFields.region_idz,
        });
        if (data.length) {
          fieldTable.value = data;
        } else fieldTable.value = [];
        if (formFields.generateType == 1) {
          formFields.parameter6 = formFields.tableNameC + '_group';
          formFields.parameter7 = formFields.tableNameC + '_list';
          const { data } = await getTabledatas({
            unit_code: formFields.tableNameC,
            region_id: formFields.region_idz,
          });
          if (data.length) {
            ChildfieldTable.value = data;
          } else ChildfieldTable.value = [];
        }
      }
    });
    setLoading(false);
  });
  const handleSelectionChange = async (value: Array<Namespace.tabledatasType>) => {
    MultiSelectDataFirst.value = value;
  };
  const handleSelectionChangeChild = async (value: Array<Namespace.tabledatasType>) => {
    MultiSelectDataNth.value = value;
  };
  const sendUpTreeData = inject('sendUpTree') as Function;
  const generate = throttle(async () => {
    if (!MultiSelectDataFirst.value.length && !MultiSelectDataNth.value.length) {
      ElMessage.info('请选择需要生成的数据！');
    } else {
      numberValue.value++;
      const dataMap = {
        region_id: props.regionId,
        ...formFields,
        data1: MultiSelectDataFirst.value,
        data2: MultiSelectDataNth.value,
      };
      const { code } = await Postgeneratepage(dataMap);
      if (code == 0) {
        setTimeout(() => {
          ElMessage.success('生成成功！');
          sendUpTreeData({ numberValue: numberValue.value, id: props.dataTree, code: 0 });
          formFields.region_idz = '';
          formFields.tableNameZ = '';
          formFields.tableNameC = '';
          formFields.relevanceZ = '';
          formFields.relevanceC = '';
          formFields.parameter1 = '';
          formFields.parameter2 = '';
          formFields.parameter3 = '';
          formFields.parameter4 = '';
          formFields.parameter5 = '';
          formFields.parameter6 = '';
          formFields.parameter7 = '';
          fieldTable.value = [];
          ChildfieldTable.value = [];
          MultiSelectDataFirst.value = [];
          MultiSelectDataNth.value = [];
          emit('update:value', false);
        }, 500);
      }
    }
  });
</script>

<style lang="scss" scoped>
  .title {
    display: table;
    background-color: var(--el-color-primary);
    position: relative;
    width: 250px;
    height: 40px;
    white-space: nowrap;
    word-break: keep-all;
    line-height: 40px;
    left: 0;
    padding-left: 50px;
    margin-bottom: 20px;
    span {
      position: relative;
      font-size: 18px;
      color: var(--el-color-white);
    }
  }
  .form-item {
    width: $width;
    :deep(.el-form-item) {
      margin-right: 0;
    }
    .button {
      :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
      }
    }
    .full {
      width: $width;
      :deep(.el-form-item__content) {
        width: 100%;
        display: flex;
        justify-content: center;
      }
    }
  }
  .form-item_textarea {
    width: $width;
    justify-content: flex-end;
    display: flex;
    :deep(.el-form-item) {
      width: $width;
    }
  }
  :deep(.el-radio-group) {
    width: $width - 50;
  }
  :deep(.el-form-item) {
    width: $width - 50;
  }
  .title::before {
    content: '';
    position: absolute;
    background-color: var(--el-color-white);
    width: 15px;
    height: 15px;
    border-radius: 50%;
    left: 20px;
    top: 50%;
    margin-top: -7.5px;
  }
  .title::after {
    content: '';
    display: block;
    position: absolute;
    border: 20.5px solid transparent;
    border-left-color: var(--el-color-primary);
    width: 0;
    height: 0;
    left: 100%;
    top: 0;
  }
  .table_content {
    &_tables {
      :deep(th) {
        color: #000;
        background-color: rgba(9, 96, 189, 0.05);
        background-image: linear-gradient(rgba(9, 96, 189, 0.1), #fff);
      }
      :deep(.el-radio) {
        margin-right: 15px;
      }
      :deep(.el-radio:last-child) {
        margin-right: 0;
      }
      :deep(.el-radio--large) {
        height: 25px;
      }
    }
  }
</style>
